
import fs from 'fs';
import path from 'path';
import * as cheerio from 'cheerio';
import { translateText, translateTextArray, isHtmlFile } from './util.js'
import he from 'he';
// 获取Documentation文件夹路径
const docsPath = path.join(process.cwd(), 'Documentation');
const outputPath = path.join(process.cwd(), 'Documentation-CN');

// 读取Documentation文件夹下所有文件内容
function readDocsFiles() {
    try {
        const files = fs.readdirSync(docsPath);
        const contents = [];
        files.forEach(file => {
            const filePath = path.join(docsPath, file);
            const stats = fs.statSync(filePath);
            if (stats.isFile() && isHtmlFile(file)) {
                const content = fs.readFileSync(filePath, 'utf-8');
                contents.push({
                    filename: file,
                    content: content
                });
            }
        });
        return contents;
    } catch (err) {
        console.error('Error reading Documentation folder:', err);
        return [];
    }
}


// 处理翻译后的html内容转义问题
function escapeHtml() {
    try {
        const files = fs.readdirSync(outputPath);
        const contents = [];
        files.forEach(file => {
            const filePath = path.join(outputPath, file);
            const stats = fs.statSync(filePath);
            if (stats.isFile() && isHtmlFile(file)) {
                console.log('正在处理转义文件：', file)
                const content = fs.readFileSync(filePath, 'utf-8');
                const resultHtml = he.decode(content);
                const outputFilePath = path.join(outputPath, file);
                fs.writeFileSync(outputFilePath, resultHtml);
            }
        });
        return contents;
    } catch (err) {
        console.error('Error reading Documentation folder:', err);
        return [];
    }
}


// 处理HTML内容
async function processHtmlContent(html) {
    const $ = cheerio.load(html, { decodeEntities: true });
    const descriptionElements = $('.description');

    const originalTextArr = []
    for (let i = 0; i < descriptionElements.length; i++) {
        const element = descriptionElements.eq(i);
        const originalText = element.html();
        originalTextArr.push(originalText)
        // const translatedText = await translateText(originalText);
        // element.text(translatedText);
    }
    const translatedTextArr = await translateTextArray(originalTextArr)

    for (let i = 0; i < translatedTextArr.length; i++) {
        const element = descriptionElements.eq(i);
        const translatedText = translatedTextArr[i];
        element.text(translatedText);
    }

    return $.html();
}

// 便利

async function main() {
    // 创建Documentation-CN文件夹
    if (!fs.existsSync(outputPath)) {
        fs.mkdirSync(outputPath);
    }

    // 读取文档文件内容
    const docsContents = readDocsFiles();

    for (const doc of docsContents) {
        const outputFilePath = path.join(outputPath, doc.filename);

        // 检查目标文件是否已存在
        if (fs.existsSync(outputFilePath)) {
            console.log(`File already exists, skipping: ${doc.filename}`);
            continue;
        }

        console.log(`Processing file: ${doc.filename}`);
        const processedHtml = await processHtmlContent(doc.content);

        // 写入到Documentation-CN文件夹
        fs.writeFileSync(outputFilePath, processedHtml);
        console.log(`Saved to: ${outputFilePath}`);
    }

    escapeHtml()
}

main();